import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import setupKnife4j from './config/swagger.config';
import { ConfigService } from '@nestjs/config';
import { AllExceptionsFilter } from './filters/exception.filter';
import { ResponseInterceptor } from './interceptors/response.interceptor';
import { Logger, ValidationPipe } from '@nestjs/common';
import { AppException } from './exceptions/AppException';
import { HttpStatusCodeEnum } from './enums/http-status-code.enum';
import { LoggingInterceptor } from './interceptors/logging.interceptor';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  setupKnife4j(app);

  // 获取 ConfigService 实例
  const configService = app.get(ConfigService);
  // 访问 .env.production 文件中的变量
  const modeName = configService.get<string>('MODE_NAME');
  console.log(`app is running on mode: ${modeName}`);
  app.useGlobalInterceptors(new ResponseInterceptor());

  app.useGlobalFilters(new AllExceptionsFilter());
  /**
   * 自定义异常提示
   */
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 自动转换请求体中的数据
      // whitelist: true, // 只允许 DTO 中定义的字段
      forbidNonWhitelisted: true, // 禁止发送未定义字段
      exceptionFactory: (errors) => {
        const messages =
          'main.ts【GlobalPipe】:' +
          errors
            .map((error) => {
              return `[${error.property}]-${Object.values(error.constraints).join(', ')}`;
            })
            .join(';');

        return new AppException(HttpStatusCodeEnum.VALID_ERROR, messages);
      },
    }),
  );

  app.useLogger(new Logger());
  // 全局注册 LoggingInterceptor
  // app.useGlobalInterceptors(new LoggingInterceptor(new Reflector()));
  await app.listen(process.env.PORT ?? 4000);
}

bootstrap();
